<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\controllers;
use Yii;
/**
 * Description of UserController
 *
 * @author Administrator
 */
class UserController extends \yii\web\Controller{
    //put your code here
    
    public function actionLogin(){
//        var_dump(Yii::$app->user->isGuest);exit;
        if(!Yii::$app->user->isGuest){
           $this->redirect(\yii\helpers\Url::toRoute("goods/list"));
        }
        if(Yii::$app->request->getIsPost()){
            $model = new \app\models\login();
            $data = Yii::$app->request->post(); //获取请求数据
            $user = $model->findByUserName($data['username']); //根据用户名查询用户信息
            if($user){
                $result = $model->validatePassword($user,$data['password']);
                if($result){
                  echo "<script>alert('登录成功');</script>";
                $this->redirect(\yii\helpers\Url::toRoute('goods/list'));
                }else{
                   echo "<script>alert('密码错误');</script>";exit;
                }
            }else{
                echo "<script>alert('用户名不存在');</script>";
                exit;
            }
            
            
        }
        
        return $this->render('login');
    }
   //注册
    public function actionRegister(){
       $model = new \app\models\login();
        $data = Yii::$app->request->post();
        if($model->load($data)){
            if($model->validate()){
                var_dump($data);
                $model->username=$data['login']['username'];               
                $model->sex=$data['login']['sex'];
                $model->password=$data['login']['password'];
                $model->age=$data['login']['age'];

                $model->save();
        }
        }
        return $this->render("user_register",['model'=>$model]); 
    }
    
    
    public function actionSession(){
        $session = Yii::$app->session;  //session类
        //存值
        $session->set('name','张三');
        $session['sex']='女';
        $_SESSION['age']=22;
        //取值
        echo $session['name'];
        echo $session->get('sex');
        echo $_SESSION['age'];
        
        //移除
        $session->remove('sex');
        unset($session['age']);
//        var_dump($session);
        //判断是否存在
       $session->has('name'); //相当于isset($_SESSION['name']); 
       
       foreach($session as $key=>$v){
           var_dump($key);
           var_dump($v);
       }
       
       $cookie=Yii::$app->response->cookies;
       //cookie存值通过 new Cookie
       $cookie->add(new \yii\web\Cookie(['name'=>'a','value'=>2]));
       echo Yii::$app->request->cookies->getValue('a');
       //删除cookie
       Yii::$app->response->cookies->remove('b');
    }
    
    
    
    
    
    
}
